package top.yehot.cmmu.shiro.session;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.redisson.api.RedissonClient;

import top.yehot.cmmu.core.utils.JSerializeUtil;

/**
 * 存储shiro session 到 redis 操作类
 * 
 * @author lquan
 * @date 2022-9-10 14:59:57
 */
public class RedisSessionDAO extends AbstractSessionDAO {
	
	private final String sessionKeyPrefix = "shiro:session:";
	// redissonClient
	private RedissonClient redissonClient;
	// session过期时间
	private Integer globalSessionTimeout;

	@Override
	public void update(Session session) throws UnknownSessionException {
		redissonClient.getBucket(sessionKeyPrefix + session.getId()).set(JSerializeUtil.serialize(session), globalSessionTimeout, TimeUnit.MINUTES);
	}

	@Override
	public void delete(Session session) {
		redissonClient.getBucket(sessionKeyPrefix + session.getId()).delete();
	}

	@Override
	public Collection<Session> getActiveSessions() {
		return Collections.emptyList();
	}

	@Override
	protected Serializable doCreate(Session session) {
		Serializable sessionId = generateSessionId(session);
		assignSessionId(session, sessionId);
		redissonClient.getBucket(sessionKeyPrefix + sessionId).set(JSerializeUtil.serialize(session), globalSessionTimeout, TimeUnit.MINUTES);
		return sessionId;
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		Object val = redissonClient.getBucket(sessionKeyPrefix + sessionId).get();
		if (Objects.isNull(val)) {
			return null;
		}
		return (Session) JSerializeUtil.deserialize(val.toString());
	}

	public void setRedissonClient(RedissonClient redissonClient) {
		this.redissonClient = redissonClient;
	}

	public void setGlobalSessionTimeout(Integer globalSessionTimeout) {
		this.globalSessionTimeout = globalSessionTimeout;
	}

}
